<!-- 线索详情页 -->
<template>
  <div class="page">
    <div class="">
      <!-- 线索基础信息 -->
      <div class="custom" :class="{ 'is-my': isMy && customInfo.leadsStatus === 1, 'is-new': isNew }">
        <div class="card-custom flex">
          <!-- <van-image round style="flex: none;" width="68px" height="68px" :src="avatar" /> -->

          <div class="custom-right" style="flex: auto;">
            <div class="custom-name fxbw aic">
              <span>{{ customInfo.name }}</span>

              <!-- 我的线索 视角 -->
              <div v-if="isMy" style="flex: none;">
                <van-button class="" round type="info" size="mini" @click="showTransfer = true">
                  转化为客户
                </van-button>
                <svg-icon
                  class="ml5"
                  style="font-size: 20px;vertical-align: middle;"
                  name="question"
                  @click="showPopup(0)"
                ></svg-icon>
              </div>
            </div>

            <div v-if="customInfo.preFollowerName" class="custom-info">
              <span class="key">前跟进人</span>
              <span class="value">{{ customInfo.preFollowerName }}</span>
            </div>

            <div class="custom-info">
              <span class="key">{{ { 0: '投放', 1: '领取', 3: '回收' }[customInfo.leadsStatus] }}时间</span>
              <span class="value">
                {{ customInfo.leadsStatus === 0 ? customInfo.createTime : customInfo.updateTime }}
              </span>
            </div>
            <!--  -->
          </div>
        </div>

        <!-- 我的线索 视角 -->
        <div class="action flex ais" v-if="isMy">
          <div class="item " @click="phoneCall(customInfo.phone)">
            <svg-icon class="icon" name="phone"></svg-icon>
            <span class="text">打电话</span>
          </div>
          <div v-if="!customInfo.externalUserid" class="item " @click="addFriend(customInfo.phone)">
            <svg-icon class="icon" name="add-friend"></svg-icon>
            <span class="text">加好友</span>
          </div>
          <div v-else class="item " @click="$router.push('/portrait')">
            <van-icon class="icon" name="user-circle-o" />
            <span class="text">客户画像</span>
          </div>
        </div>
      </div>

      <!-- 新线索 -->
      <template v-if="isNew">
        <van-cell title="手机号码" :value="customInfo.phone || '-'" />
        <van-cell title="性别" :value="customInfo.sexStr || '-'" />
        <van-cell title="线索来源" :value="customInfo.sourceStr || '-'" />
        <!-- <van-cell title="年龄" :value="customInfo.age || '-'" /> -->
        <van-cell
          v-for="(item, index) in customInfo.propertiesList"
          :key="index"
          :title="item.name"
          :value="item.value || '-'"
        />
      </template>

      <template v-else>
        <!-- 标签信息 -->
        <!-- 我的跟进线索或者线索便签存在时 显示 -->
        <div v-if="customInfo.labelsNames || isMy" class="labels">
          <template v-if="isMy">
            <div class="label-t mb10">
              <span>标签信息</span>
              <span class="btn-edit" @click="showEdit = true">修改</span>
            </div>
          </template>

          <TagEllipsis :list="tags" :limit="8" />

          <!-- 我的跟进下 显示空状态 -->
          <Empty v-if="!customInfo.labelsNames && isMy" style="height: 116px;" />
        </div>

        <van-tabs ref="tabs" class="detail-tab">
          <!-- 我的跟进 -->
          <van-tab title="我的跟进" name="follow" v-if="isMy">
            <Record :leadId="leadsId" :followUserId="customInfo.followerId" ref="record" />
          </van-tab>

          <!-- 任意状态下的【详细资料】tab -->
          <van-tab title="详细资料" name="detail">
            <van-cell title="手机号码" :value="customInfo.phone || '-'" />
            <van-cell title="性别" :value="customInfo.sexStr || '-'" />
            <van-cell title="线索来源" :value="customInfo.sourceStr || '-'" />
            <!-- <van-cell title="年龄" :value="customInfo.age || '-'" /> -->
            <template v-if="customInfo.propertiesList">
              <van-cell
                v-for="(item, index) in customInfo.propertiesList"
                :key="index"
                :title="item.name"
                :value="item.value || '-'"
              />
            </template>
          </van-tab>

          <!-- 跟进中、已退回状态下的【前跟进人记录】tab -->
          <van-tab v-if="[1, 3].includes(customInfo.leadsStatus)" title="前跟进人记录" name="record">
            <!--  -->
            <van-tabs>
              <van-tab v-for="(card, index) in beforeFollowUp" :key="index">
                <template #title>
                  <!-- <van-image round width="28px" height="28px" :src="card.url" /> -->
                  <span>{{ card.followUserName }}</span>
                </template>

                <Record :id="card.id" ref="record2" />
              </van-tab>
            </van-tabs>
            <!--  -->
          </van-tab>
        </van-tabs>
      </template>
    </div>

    <div class="footer">
      <van-button v-if="[0, 3].includes(customInfo.leadsStatus)" type="info" round block @click="collectClue">
        领取线索
      </van-button>

      <!-- 跟进中提供【添加跟进】与【线索退回】按钮 -->
      <div class=" flex " v-if="isMy && [1].includes(customInfo.leadsStatus)">
        <van-button type="danger" round block @click="showBack = true">线索退回</van-button>
        <van-button type="info" round block class="ml10" @click="showFollowup = true">添加跟进</van-button>
      </div>
    </div>

    <!-- 线索标签信息修改 弹窗 -->
    <edit v-model="showEdit" :leadData="customInfo" @success="updateInfo" />

    <!-- 线索退回 弹窗 -->
    <back v-model="showBack" :leadId="leadsId" @success="updateInfo" />

    <!-- 转为客户 弹窗 -->
    <transfer v-model="showTransfer" :leadId="leadsId" @success="updateInfo" />

    <!-- 添加跟进 弹窗 -->
    <followup v-model="showFollowup" title="添加跟进" :leadId="leadsId" @success="$refs.record.getList(1)" />

    <!-- 预览 -->
  </div>
</template>

<script>
import TagEllipsis from '@/components/TagEllipsis.vue'
import Record from './components/Record.vue'
import back from './back'
import edit from './edit'
import transfer from './transfer'
import followup from './followup'
import { receive, getLeadsDeatail, getFollowUpList, getFollowRecordList, getEntranceHistory } from './api'

export default {
  components: { TagEllipsis, Record, back, edit, transfer, followup },
  props: {},
  data() {
    return {
      // 预览
      isPreview: false,
      previewUrl: [],
      previewType: 0,
      isNew: false,
      isMy: false,
      userId: sessionStorage.getItem('sysId'),
      // avatar: customerAatars[Math.round(Math.random() * 10)],
      leadsId: undefined,
      customInfo: {
        //   id: null,
        //   name: '人格热水',
        //   phone: '',
        //   age: null,
        //   sex: null,
        //   symptom: null,
        //   appointmentTime: null,
        //   leavePhoneTime: '',
        //   link: null,
        //   primaryChannel: null,
        //   primaryChannelName: null,
        //   secondaryChannel: null,
        //   secondaryChannelName: null,
        //   threeLevelChannel: null,
        //   threeLevelChannelName: null,
        //   subject: null,
        //   leadsStatus: null,
        //   state: null,
        //   leadsPendingStatus: null,
        //   leadsPendingStatusName: '',
        //   kinship: '',
        //   secondaryRelation: '',
        //   nearbyArea: null,
        //   nearbyAreaName: null,
        //   userJobNumber: null,
        //   userJobName: null,
        //   recoveryTimes: null,
        //   returnReason: null,
        //   labelsIds: '1,2,65,495,6,26,56,65,5,',
        //   labelsNames:
        //     'sdfasef,46464,人格热水,跟人啊二色,46464,人格热水,跟人啊二色,46464,人格热水,跟人啊二色,46464,人格热水,跟人啊二色,46464,人格热水,跟人啊二色,46464,人格热水,跟人啊二色',
        //   weixinStatus: null,
        //   weixinId: null,
        //   consult: '',
        //   seaId: '',
        //   propertiesList: [],
      },
      beforeFollowUp: [],

      showBack: false,
      showEdit: false,
      showTransfer: false,
      showFollowup: false,
    }
  },
  computed: {
    tags() {
      let name = []
      if (this.customInfo.labelsNames) {
        name = this.customInfo.labelsNames.split(',')
      }
      return name
    },
    // isShowBeforeRecord() {
    //   return this.beforeFollowUp.length > 0 && [0, 3].includes(this.customInfo.leadsStatus)
    // },
    // isShowRecord() {
    //   return this.beforeFollowUp.length > 0 && [1, 4].includes(this.customInfo.leadsStatus)
    // },
  },
  watch: {},
  created() {
    this.leadsId = this.$route.query.id
  },
  async mounted() {
    this.updateInfo()
  },
  methods: {
    showPopup() {
      this.$dialog.alert({
        title: '线索转化',
        message:
          '转化为客户则代表该线索已成为企业的有效客户资源，需选择同一手机号的微信好友进行绑定关联进行后续跟进。如未添加该线索为好友，请尽快添加。',
        theme: 'round-button',
        confirmButtonText: '我知道了',
      })
    },
    previewFile(url, type) {
      this.previewUrl = [url]
      this.previewType = type
      this.isPreview = true
    },
    async updateInfo() {
      await this.getLeadsDeatail()
      this.getFollowUpList()
    },
    async getLeadsDeatail() {
      const toast = this.$toast.loading()
      await getLeadsDeatail(this.leadsId)
        .then(({ data }) => {
          if (data === '暂无权限查看该线索') {
            // this.showDetail = false
            this.customInfo = {}
          } else {
            this.customInfo = data || {}
            this.editForm = data
            this.isNew = data.leadsStatus === 0
            toast.clear()
          }
        })
        .catch((err) => {
          toast.clear()
        })
    },
    // 获取跟进人名单
    getFollowUpList() {
      getFollowUpList(this.leadsId).then(({ data }) => {
        // const data = data.map((e) => ({
        //   ...e,
        //   url: customerAatars[Math.round(Math.random() * 10)],
        // }))

        if (data && data[0]) {
          this.isMy = this.userId == data[0].followerId && data[0].followerStatus == 1
          if (this.isMy) {
            this.beforeFollowUp = data.slice(1)
          } else {
            this.beforeFollowUp = data
          }
        }
      })
    },

    // 打电话
    phoneCall(phone) {
      if (phone) {
        window.location.href = 'tel:' + phone
      }
    },
    handleCopy(text) {
      const input = document.createElement('input')
      input.style.cssText = 'opacity: 0;'
      input.type = 'text'
      input.value = text // 修改文本框的内容
      document.body.appendChild(input)
      input.select() // 选中文本
      document.execCommand('copy') // 执行浏览器复制命令
      // this.$message({ message: '微信已复制到剪切板', type: 'success' })
      this.$toast.success('微信号已复制到剪切板')
    },
    // 加好友
    addFriend(phone) {
      if (phone) {
        this.handleCopy(phone)
        setTimeout(() => {
          wx.invoke('navigateToAddCustomer', {}, function(res) {
            console.log(res)
          })
        }, 500)
      }
      wx.invoke('navigateToAddCustomer', {}, function(res) {
        console.log(res)
      })
    },
    // 领取线索
    collectClue() {
      this.$dialog
        .confirm({
          title: '领取线索',
          message: '是否确认领取该线索客户进行跟进？',
        })
        .then(() => {
          this.$toast.loading()
          return receive(this.leadsId)
        })
        .then((res) => {
          this.$toast.success('操作成功')
          this.updateInfo()
        })
        .finally(() => {
          this.$toast.clear()
        })
    },
  },
}
</script>

<style lang="less" scoped>
.page {
  padding-bottom: 64px;
}
.footer {
  position: absolute;
  width: 100%;
  bottom: 0;
  padding: 10px;
  z-index: 9;
  background: #fff;
}
.custom {
  background: #fff;
  padding: 15px;
  .custom-right {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    margin-left: 10px;
  }
  .custom-info {
    margin-top: 8px;
    font-size: 12px;
    .key {
      color: #b5b8c0;
    }
    .value {
      margin-left: 10px;
      color: #5f6063;
    }
  }
}
.shadow {
  box-shadow: 0px 2px 4px 0px #e2e8f0;
}
.custom {
  .action {
    position: relative;
    margin: 10px 25px 0;
    background: #fff;
    box-shadow: 0px 0 6px 0px rgba(0, 0, 0, 0.02);
    border-radius: 12px;
    .item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      .icon {
        font-size: 16px;
        color: @color;
        margin-right: 5px;
      }
      .text {
        font-size: 12px;
        color: #4e5969;
      }
    }
    .call {
      border-right: 1px solid #e5e5e5;
    }
  }
  &.is-new {
    background: #fff;
    box-shadow: 0px 2px 4px 0px #e2e8f0;
    margin-bottom: 10px;
  }
  &.is-my {
    .bg {
      display: block;
    }
    .avartar {
      color: #fff;
      .con {
        .status {
          border: 1px solid #fff;
          color: #fff;
        }
      }
    }
    .action {
      display: flex;
    }
  }
}
.labels {
  margin-top: 10px;
  background: #fff;
  box-shadow: 0px 0px 1px 0px rgba(0, 0, 0, 0.02), 0px 40px 20px 0px rgba(0, 0, 0, 0.02);
  border-radius: 12px;
  padding: 15px;
  .btn-edit {
    float: right;
    color: @color;
    font-size: 12px;
  }

  .card-tag {
    display: flex;
    flex-wrap: wrap;
    margin-top: 16px;
    gap: 10px;
    .tag {
      border-radius: 13px;
      background: #d3f2ff;
      line-height: 15px;
      padding: 5px 10px;
      font-size: 9px;
      font-weight: 400;
      color: @color;
    }
  }
  .btn {
    font-size: 10px;
    color: #86909c;
    text-align: center;
  }
}
.detail-tab {
  margin: 20px 0 0;
  ::v-deep .van-tabs__content {
    height: calc(100vh - 108px);
    overflow: auto;
  }
}
</style>
